using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 物理护盾Buff - 吸收物理伤害
/// </summary>
public class PhysicalShieldBuff : BuffBase
{
    private long m_ShieldAmount;
    private long m_CurrentShield;
    private bool m_IsShieldActive;

    public PhysicalShieldBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is PhysicalShieldData shieldData)
        {
            m_ShieldAmount = shieldData.ShieldAmount;
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        m_CurrentShield = m_ShieldAmount;
        m_IsShieldActive = true;
        
        // 播放护盾特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        // 设置护盾状���
        Target.HealthComponent.SetPhysicalShield(true);
        
        Logger.Log($"{Target.name} 获得物理护盾，吸���{m_ShieldAmount} 点物理伤���");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        // 护盾期间不需要特殊处���
    }

    /// <summary>
    /// 处理护盾伤害
    /// </summary>
    /// <param name="damage">伤害���/param>
    /// <returns>剩余伤害</returns>
    public long ProcessShieldDamage(long damage)
    {
        if (!m_IsShieldActive || m_CurrentShield <= 0)
        {
            return damage;
        }

        long absorbedDamage = Math.Min(damage, m_CurrentShield);
        m_CurrentShield -= absorbedDamage;
        
        Logger.Log($"{Target.name} 护盾吸收���{absorbedDamage} 点伤害，剩余护盾: {m_CurrentShield}");
        
        // 如果护盾被完全破���
        if (m_CurrentShield <= 0)
        {
            m_IsShieldActive = false;
            Target.HealthComponent.SetPhysicalShield(false);
            Logger.Log($"{Target.name} 护盾被破���");
        }
        
        return damage - absorbedDamage;
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log($"{Target.name} 护盾效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        
        // 移除护盾状���
        Target.HealthComponent.SetPhysicalShield(false);
        
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("PhysicalShield"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return true; // 护盾效果可以叠加，增加护盾���
    }

    /// <summary>
    /// 获取当前护盾���
    /// </summary>
    public long GetCurrentShield()
    {
        return m_CurrentShield;
    }

    /// <summary>
    /// 检查护盾是否激���
    /// </summary>
    public bool IsShieldActive()
    {
        return m_IsShieldActive && m_CurrentShield > 0;
    }
}
